﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhiStore.Threading;
using System.IO;

namespace FileSystemAnalysis.Code
{
    class Producer : Boostable
    {
        private Channel<string> outputChannel;
        private string basePath;
        private Model model;
        public Producer(string basePath, Channel<string> outputChannel, Model model)
        {
            this.outputChannel = outputChannel;
            this.basePath = basePath;
            this.model = model;
        }

        public void Run()
        {
            model.Running = true;
            model.Indexing = true;
            browseDirectory(basePath);
            outputChannel.Poison();
            model.Indexing = false;
        }

        private void browseDirectory(string path)
        {
            try
            {
                string[] files = Directory.GetFiles(path);
                foreach (string file in files)
                {
                    outputChannel.Send(file);
                }
                string[] dirs = Directory.GetDirectories(path);
                foreach (string dir in dirs)
                { //recursive call
                    browseDirectory(dir);
                }
            }
            catch (UnauthorizedAccessException)
            {
                //ignore directory
            }
            catch (PoisonException)
            {
                //brute force stop initiated
            }
        }
    }
}
